package com.framework.loippi.controller.api;

import com.framework.loippi.api.utils.ApiUtils;
import com.framework.loippi.entity.Details;
import com.framework.loippi.entity.TPreferential;
import com.framework.loippi.service.DetailsService;
import com.framework.loippi.service.TPreferentialService;
import com.sun.org.apache.xml.internal.resolver.readers.ExtendedXMLCatalogReader;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

@Controller("apiMedicineDetailController2")
@Api(tags = "药品详情信息")
@RequestMapping("/api/detail2")
public class MedicineDetailController2 extends ApiBaseController {

    @Resource
    DetailsService detailsService;

    @Resource
    TPreferentialService preferentialService;


    /**
     * 根据用户id和药物id查询药品的详细信息和这个药品对于当前用户的优惠以后的实际价格
     *
     * @param gid
     * @param uid
     * @return
     */
    @RequestMapping(value = "/findById.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "根据id查询药品详情", notes = "{}")
    public @ResponseBody
    String findById(Long gid,Long uid) {
        try {
            Details details = detailsService.find(gid);
            TPreferential preferential = preferentialService.findByUidGid(uid,gid);
            if(null==preferential){
                return ApiUtils.error();
            }
            BigDecimal percentage = preferential.getPreferential().setScale(3);
            BigDecimal actullPrice = details.getSalesPrice().multiply(percentage).setScale(3);
            Map<String,Object> result = new HashMap<>();
            result.put("deatil",details);
            result.put("actuallPrice",actullPrice);
            return ApiUtils.success(result);
        }catch (Exception e){
            System.err.println("查询异常");
            e.printStackTrace();
            return ApiUtils.error();
        }

    }


    /**
     * 在被推荐用户购买完成以后 更新当前用户的优惠比例
     * @param uid  推荐人id
     * @param gid  推荐药物id
     * @return
     */
    @RequestMapping(value = "/update.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "根据用户ID和药物id更新药物推荐人的优惠比例", notes = "{}")
    public @ResponseBody
    String update(Long uid,Long gid) {
       preferentialService.updateByUidAndGid(uid,gid);
       return ApiUtils.success();
    }
}
